﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Swashbuckle
{
    public class Tools
    {
        /// <summary>
        /// Http (GET/POST)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应内容</returns>
        public static string SendPost(string url, IDictionary<string, string> parameters, string method)
        {
            if (method.ToLower() == "post")
            {
                HttpWebResponse rsp = null;
                System.IO.Stream reqStream = null;
                try
                {
                    HttpWebRequest req = null;
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = method;
                    req.KeepAlive = false;
                    req.ProtocolVersion = HttpVersion.Version10;
                    req.Timeout = 5000;
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                    reqStream = req.GetRequestStream();
                    reqStream.Write(postData, 0, postData.Length);
                    rsp = (HttpWebResponse)req.GetResponse();
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponseAsString(rsp, encoding);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                finally
                {
                    if (reqStream != null) reqStream.Close();
                    if (rsp != null) rsp.Close();
                }
            }
            else
            {
                //创建请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));

                //GET请求
                request.Method = "GET";
                request.ReadWriteTimeout = 5000;
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

                //返回内容
                string retString = myStreamReader.ReadToEnd();
                return retString;
            }
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

       public static string GetData()
        {
            HttpWebRequest req = null;
            req = (HttpWebRequest)WebRequest.Create("http://restapi.amap.com/v3/geocode/regeo");
            req.Headers.Add("Connection", "close");
            req.Headers.Add("logversion", "2.1");
            req.Headers.Add("platinfo", "platform=Android&sdkversion=6.9.2&product=sea");
            req.Headers.Add("X-INFO", "dvAtst9zRqviJYr3wz+NmAnyZzHKDRXa9FmB20nPsis8fBWyXravI5kp+bopTnxgQ4PcVnRYMDt7GUIl0HX8GC0DkCBsGU9k/a0tX4KQKUvyElsBA/g+m+Gb8SWJ0GtB18qIdUuWqx9aTXviolXe7nhvBWkYyIOv0jaqoGQqejoKXbt80hyvT7lbJh5Oq+ZpOndv7+Cq2jpouGub8yepH9KLYXt693p6/3V69f3Px7dbeqnMUizIZxekcOIakRRn5EKq7V/fvkwffv7+9GN683khxMsQoHKQhycoCcGFEZAEV4EVgoRThQ9gA6nBETzXqHAOpOEVRIBwqOpiNtHBBNQSeqb5IgXkEtIhztuZ7AubQ8wQDR2RJzi7w+H/L6FikAGli1JJysdREuWGnKKz66HNsuyKtTEqa2syRGZttDaHlbEp1YFMkPvcxNJ4dsaJaLUm0rkZu3+p8s7GueSqKtazxiH1DR+V4/C863mdSimNny97bktrlBq5D4cl9+3GHf0FcOSIG6sBAAA=");
            req.Headers.Add("User-Agent", "AMAP SDK Android Search 6.9.2");
            req.Headers.Add("Accept-Encoding", "gzip");
            req.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            req.Headers.Add("csid", "c3a7abaacbbb413fa8eeac3948f1fdec");
            req.Headers.Add("Host", "restapi.amap.com");
            req.Headers.Add("Content-Length", "193");
            req.Method = "Post";
            byte[] postData = Encoding.UTF8.GetBytes("output=json&extensions=all&location=106.516042,29.511721&radius=200&coordsys=autonavi&key=a05819da34c47fa53324b7bb5ab72fd0&language=zh-CN&ts=1585191789017&scode=4adbe185f43664915ab2a4d007f23264");
            System.IO.Stream reqStream = null;
            reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            HttpWebResponse rsp = null;
            rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }
    }
}
